//
//  NSDictionary+THHook.m
//  MengLiao
//
//  Created by xiuxin on 2022/7/14.
//  Copyright © 2022 BaseBusiness. All rights reserved.
//

#import "NSDictionary+THHook.h"
#import "THDeBugTool.h"
#import "THCrashManager.h"
@implementation NSDictionary (THHook)

+ (void)load{
#ifdef DEBUG
    return;
#endif
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        ExchangeImplementationsInTwoClasses([NSDictionary class], @selector(dictionaryWithObjects:forKeys:count:), [NSDictionary class], @selector(avoidCrashDictionaryWithObjects:forKeys:count:));
        ExchangeImplementationsInTwoClasses(NSClassFromString(@"__NSPlaceholderDictionary"), @selector(initWithObjects:forKeys:count:), [NSDictionary class], @selector(avoidCrash_initWithObjects:forKeys:count:));
    });
}
+ (instancetype)avoidCrashDictionaryWithObjects:(const id  _Nonnull __unsafe_unretained *)objects forKeys:(const id<NSCopying>  _Nonnull __unsafe_unretained *)keys count:(NSUInteger)cnt {
    id instance = nil;
    @try {
        instance = [self avoidCrashDictionaryWithObjects:objects forKeys:keys count:cnt];
    }
    @catch (NSException *exception) {
        [[THCrashManager shareInstance] reportExp:exception];
        //处理错误的数据，然后重新初始化一个字典
        NSUInteger index = 0;
        id  _Nonnull __unsafe_unretained newObjects[cnt];
        id  _Nonnull __unsafe_unretained newkeys[cnt];
        
        for (int i = 0; i < cnt; i++) {
            if (objects[i] && keys[i]) {
                newObjects[index] = objects[i];
                newkeys[index] = keys[i];
                index++;
            }
        }
        instance = [self avoidCrashDictionaryWithObjects:newObjects forKeys:newkeys count:index];
    }
    @finally {
        return instance;
    }
}
- (instancetype)avoidCrash_initWithObjects:(id  _Nonnull const [])objects
                          forKeys:(id<NSCopying>  _Nonnull const [])keys
                            count:(NSUInteger)cnt{
    id _Nonnull  safeObjects[cnt];
    id  <NSCopying> _Nonnull safeKeys[cnt];
    NSUInteger j = 0;
    for (NSUInteger i = 0; i < cnt ; i++) {
        if (keys[i] && objects[i]) {
            safeObjects[j] = objects[i];
            safeKeys[j]    = keys[i];
            j++;
        }else{
#ifdef DEBUG
     NSString *errorDes = [NSString stringWithFormat:@"__NSPlaceholderDictionary (THHook) - 不合法的key或者objects\n%@",[NSThread callStackSymbols]];
     NSLog(@"%@",errorDes);
#else
     NSString *errorDes = [NSString stringWithFormat:@"__NSPlaceholderDictionary (THHook)- 不合法的key或者objects\n%@",[NSThread callStackSymbols]];
     NSError *error = [NSError errorWithDomain:@"huanque" code:10003 userInfo:@{NSLocalizedDescriptionKey:errorDes}];
     [[THCrashManager shareInstance] reportError:error];
#endif
        }
    }
    return [self avoidCrash_initWithObjects:safeObjects forKeys:safeKeys count:j];
}

@end
